//
// Created by 11510 on 2024/7/29.
//

#ifndef WEB_LIBRARY_DIRSCANNER_H
#define WEB_LIBRARY_DIRSCANNER_H
#include <dirent.h>
#include <sys/stat.h>
#include <unistd.h>
#include <vector>
#include <string>
#include <iostream>

class DirScanner {
private:
    std::vector<std::string> files;

public:
    const std::vector<std::string>& getFiles()const{
        return files;
    }

    void traverse(const std::string& directory){
        DIR *dir;
        struct dirent *entry;
        struct stat info;

        if ((dir = opendir(directory.c_str())) != nullptr) {
            while ((entry = readdir(dir)) != nullptr) {
                std::string path = directory + "/" + entry->d_name;

                if (entry->d_type == DT_DIR) {
                    // 忽略 "." 和 ".."
                    if (std::string(entry->d_name) == "." || std::string(entry->d_name) == "..")
                        continue;
                    // 递归处理子目录
                    traverse(path);
                } else {
                    // 检查是否为常规文件
                    if (stat(path.c_str(), &info) == 0 && S_ISREG(info.st_mode)) {
                        // 获取绝对路径
                        char real_path[PATH_MAX];
                        realpath(path.c_str(), real_path);
                        files.push_back(std::string(real_path));
                    }
                }
            }
            closedir(dir);
        } else {
            std::cerr << "无法打开目录: " << directory << std::endl;
        }
    }

    void operator()(const std::string& directory){
        traverse(directory);
    }
};


#endif //WEB_LIBRARY_DIRSCANNER_H
